﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RaygunDiplomacy.Model.Terrain.Local
{
   public class ChunkVisibility
   {
      VisibilitySection[] sections;

      public void SetupVisibility(ChunkCells cells)
      {
         var transparentCellIndicies = (from row in Enumerable.Range(0, ChunkCells.ChunkSize)
                                from column in Enumerable.Range(0, ChunkCells.ChunkSize)
                                from sheet in Enumerable.Range(0, ChunkCells.ChunkSize)
                                let index = new SpatialIndex(row, column, sheet)
                                where cells[index].CellTemplate.IsTransparent
                                select index).ToList();

         List<VisibilitySection> newSections = new List<VisibilitySection>();

         while (transparentCellIndicies.Any())
         {
            var sectionCells = new List<SpatialIndex>();
            var toCheck = new Queue<SpatialIndex>();
            var cellIndex = transparentCellIndicies.First();

            toCheck.Enqueue(cellIndex);
            sectionCells.Add(cellIndex);
            transparentCellIndicies.Remove(cellIndex);

            while (toCheck.Any())
            {
               cellIndex = toCheck.Dequeue();
               var adjacent = from index in cellIndex.AdjacentIndices(ChunkCells.MaxIndex)
                              where cells[index].CellTemplate.IsTransparent && transparentCellIndicies.Contains(index)
                              select index;

               foreach (var index in adjacent)
               {
                  toCheck.Enqueue(index);
                  sectionCells.Add(index);
                  transparentCellIndicies.Remove(index);
               }
            }

            newSections.Add(new VisibilitySection(sectionCells));
         }
      }

      public void UpdateVisibility(ChunkCells cells, IEnumerable<SpatialIndex> changedCells)
      {

      }
   }
}
